package dongze.com.ckdj.fragment.custom;

import android.app.Activity;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dongze.com.ckdj.R;
import dongze.com.ckdj.activity.AddMassLossRecordActivity;
import dongze.com.ckdj.activity.SelectCheckPointActivity;
import dongze.com.ckdj.activity.custom.MartinPhotoCheckInActivity;
import dongze.com.ckdj.adapter.ListItem;
import dongze.com.ckdj.adapter.VehicleInformationAdapter;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.data.entity.request.Record;
import dongze.com.ckdj.data.entity.request.RecordRequestBody;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;
import dongze.com.ckdj.databinding.model.MassLossImageItemModel;
import dongze.com.ckdj.fragment.ProcessableFragment;
import dongze.com.ckdj.persistence.DaoHelper;
import dongze.com.ckdj.persistence.dao.DaoSession;
import dongze.com.ckdj.service.IImageUploadService;
import dongze.com.ckdj.service.ImageUploadTask;
import dongze.com.ckdj.ui.ImageUploadDialog;
import dongze.com.ckdj.util.MyLog;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/12/18.
 */

public class MartinVehicleInformationFragment extends ProcessableFragment implements AdapterView.OnItemClickListener {
    private static final String TAG = MartinVehicleInformationFragment.class.getSimpleName();
    private static final int REQUEST_CODE_TIRE = 2001;
    private static final int REQUEST_CODE = 2002;
    @BindView(R.id.save_record)
    Button saveBtn;
    @BindView(R.id.infomation_list)
    ListView listView;
    VehicleInformationAdapter adapter = new VehicleInformationAdapter();
    ListItem[] listItems;
    Map<ListItem, List<Pair<Integer, String>>> listItemListMap = new HashMap<>();

    @Inject
    VehicleInformationDetail vehicleInformationDetail;
    @Inject
    InspectionSectionResponse mInspectionSection;
    @Inject
    User user;
    @Inject
    DaoSession daoSession;
    IImageUploadService mService;
    ServiceConnection mConn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            MyLog.d(TAG, "onServiceConnected: ");
            mService = IImageUploadService.Stub.asInterface(service);
//            try {
//                mService.addCallback(mBinder);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            MyLog.d(TAG, "onServiceDisconnected: ");
//            try {
//                mService.removeCallback(mBinder);
//            } catch (RemoteException e) {
//                e.printStackTrace();
//            }
            mService = null;
        }
    };
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getComponent(VehicleComponent.class) != null) {
            getComponent(VehicleComponent.class).inject(this);
        } else {
            getFragmentManager().beginTransaction().remove(this).commit();
        }

        if (vehicleInformationDetail != null
                && vehicleInformationDetail.getVin_info() != null
                && vehicleInformationDetail.getVin_info().size() != 0) {
            listItems = new ListItem[vehicleInformationDetail.getVin_info().size()];

            for (int i = 0; i < listItems.length; i++) {
                listItems[i] = new ListItem();
                listItems[i].setKey(vehicleInformationDetail.getVin_info().get(i).getKey());
                listItems[i].setValue(vehicleInformationDetail.getVin_info().get(i).getValue());
            }

            doProcessing();
            buildInfomationModel();
        }
    }

    @Nullable
    @Override
    public View createContentView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_vehicle_information, container, false);
        ButterKnife.bind(this, root);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        buildInfomationModel();

        if (listItems == null || listItems.length == 0)
            saveBtn.setEnabled(false);

        return root;
    }

    @OnClick(R.id.save_record)
    public void save(View view) {
        if (listItems == null || listItems.length == 0)
            return;

        List<ImageUploadTask> tasks = new ArrayList<>();
        List<File> images = new ArrayList<>();

        for (Map.Entry<ListItem, List<Pair<Integer, String>>> i :
                listItemListMap.entrySet()) {
            if (i.getValue() != null) {
                for (Pair<Integer, String> p : i.getValue()) {
                    ImageUploadTask task = DaoHelper.createMartinCheckInTask(daoSession,
                            vehicleInformationDetail.getVin(),
                            user.getUser_no(),
                            i.getKey().getKey(),
                            p.first,
                            p.second);
                    tasks.add(task);
                    images.add(new File(p.second));
                }

            }
        }

        if (tasks.size() == 0) {
            return;
        }

        ImageUploadDialog imageUploadDialog = new ImageUploadDialog(getActivity(), tasks, images, null);
        imageUploadDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                listItemListMap.clear();
                for (ListItem i :
                        listItems) {
                    i.setValue("");
                }
                adapter.notifyDataSetChanged();
            }
        });
        imageUploadDialog.show();
    }

    private void buildInfomationModel() {
        if (listView != null && listItems != null) {
            adapter.setListItems(listItems);
            adapter.notifyDataSetChanged();
            finishProcessing();
        }
    }

    @OnClick(R.id.mass_loss_btn)
    void onMassLossBtnClick(View view) {
        SelectCheckPointActivity.actionStart(getActivity(), vehicleInformationDetail.getVoyage(), vehicleInformationDetail.getType(), "", "");
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent;
        intent = new Intent(view.getContext().getApplicationContext(), MartinPhotoCheckInActivity.class);
        intent.putExtra("key", listItems[position].getKey());
        intent.putExtra("vin", vehicleInformationDetail.getVin());
        if (listItemListMap.get(listItems[position]) != null)
            intent.putExtra("value", new Gson().toJson(listItemListMap.get(listItems[position])));
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                String key = data.getStringExtra("key");
                String liststr = data.getStringExtra("value");
                List<Pair<Integer, String>> list = new Gson().fromJson(liststr, new TypeToken<List<Pair<Integer, String>>>() {
                }.getType());
                if (!TextUtils.isEmpty(key)) {
                    for (ListItem i :
                            listItems) {
                        if (TextUtils.equals(i.getKey(), key)) {
                            listItemListMap.put(i, list);
                            i.setValue("" + list.size() + "张照片");
                            adapter.notifyDataSetChanged();
                            break;
                        }
                    }
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
